package com.mr.sell.aspect;

import com.mr.sell.constant.Constant;
import com.mr.sell.exception.AuthorizeException;
import com.mr.sell.exception.CustomException;
import com.mr.sell.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Class: SellerAuthorizeAspect
 * User (作者):MRui
 * TODO (描述)：身份验证AOP校验（登陆登出）
 * Date 2018.10.04 14:08
 */
@Slf4j
@Aspect
@Component
public class SellerAuthorizeAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
    * User (作者): MRui
    * TODO (描述) 拦截规则
    * Data：2018.10.04 14:19
    */
    @Pointcut("execution(public * com.mr.sell.controller.Seller*.*(..))"+
    "&& !execution(public * com.mr.sell.controller.SellerInfoController.*(..))")
    public void verify(){}

    /**
    * User (作者): MRui
    * TODO (描述)：拦截之前
    * Data：2018.10.04 14:19
    */
    @Before("verify()")
    public void doVerify(){
        //获取request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取cookie
        Cookie cookie = CookieUtil.get(request, Constant.COOKIE_TOKEN);
        if (cookie != null){
            log.warn("[登录校验]Cookie中查不到token");
            throw new AuthorizeException();
        }
        //去redis查询
        String tokenValue = redisTemplate.opsForValue().get(String.format(Constant.REDIS_TOKEN_PREFIX, cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)){
            log.warn("[登录校验]Cookie中查不到token");
            throw new AuthorizeException();
        }
    }
}
